<?php

namespace app\admin\controller;

use app\common\controller\AdminController;

//引入外部函数
use app\common\model\hfztcy\LibConfig;
use app\common\model\hfztcy\LibMemberDistribute;
use app\common\model\hfztcy\LibMemberTeamChange;
use app\common\model\hfztcy\LibOrderVip;
use app\common\model\hfztcy\LibUserVideoAuth;
use app\common\model\LibUser;
use app\common\model\hfztcy\LibMember;
use common\Common;
use think\Db;
use think\exception\ErrorException;


/**
 * 会员
 * @name Member.php
 * @package hfztcy
 * @category controller
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2020-6-5
 */
class Member extends AdminController
{
    public $model;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new LibMember();
        $this->rightVerify(session('admin'), url("admin/Login/login"));
        parent::__construct();
    }

    /**
     * 游客提交资料审核列表页
     */
    function memberAuditList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "资料审核列表页", 1, 'view');
        return $this->fetch('Member/memberAuditList/memberList');
    }

    /**
     * 游客列表页
     */
    function memberGuestList()
    {
        $this->getSetMenu($this);
        $sql = "SELECT count(*) num FROM `base_user` WHERE FIND_IN_SET(0,identity)";
        $query = Db::query($sql);
        $this->assign('query',$query);
        $this->log(__CLASS__, __FUNCTION__, "游客-列表页", 1, 'view');
        return $this->fetch('Member/memberGuestList/memberList');
    }

    /**
     * 普通会员列表页
     */
    function memberList()
    {
        $this->getSetMenu($this);
        $sql = "SELECT count(*) num FROM `hfztcy_user` WHERE FIND_IN_SET(1,state) AND audit_state = 1";
        $query = Db::query($sql);
        $this->assign('query',$query);
        $this->log(__CLASS__, __FUNCTION__, "普通会员-列表页", 1, 'view');
        return $this->fetch('Member/memberList/memberList');
    }

    /**
     * 团队列表页
     */
    function memberTeamList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "团队-列表页", 1, 'view');
        return $this->fetch('Member/memberTeamList/memberList');
    }

    /**
     * vip会员列表页
     */
    function memberVipList()
    {
        $this->getSetMenu($this);
        $sql = "SELECT count(*) num FROM `hfztcy_user` WHERE FIND_IN_SET(2,state) AND audit_state = 1";
        $query = Db::query($sql);
        $this->assign('query',$query);
        $this->log(__CLASS__, __FUNCTION__, "VIP会员-列表页", 1, 'view');
        return $this->fetch('Member/memberVipList/memberList');
    }

    /**
     * vip会员列表页
     */
    function memberVideoList()
    {
        $this->getSetMenu($this);
        $sql = "SELECT count(*) num FROM `hfztcy_user` WHERE is_vip_video > 0 AND audit_state = 1";
        $query = Db::query($sql);
        $this->assign('query',$query);
        $this->log(__CLASS__, __FUNCTION__, "栏目认证会员-列表页", 1, 'view');
        return $this->fetch('Member/memberVideoList/memberList');
    }

    /**
     * 红娘认证会员列表页
     */
    function memberRedMotherList()
    {
        $this->getSetMenu($this);
        $sql = "SELECT count(*) num FROM `hfztcy_user` WHERE FIND_IN_SET(3,state) AND audit_state = 1";
        $query = Db::query($sql);
        $this->assign('query',$query);
        $this->log(__CLASS__, __FUNCTION__, "红娘认证会员-列表页", 1, 'view');
        return $this->fetch('Member/memberRedMotherList/memberList');
    }

    /**
     * 门店列表页
     */
    function memberStoreList()
    {
        $this->getSetMenu($this);
        $sql = "SELECT count(*) num FROM `hfztcy_user` WHERE FIND_IN_SET(4,state) AND audit_state = 1";
        $query = Db::query($sql);
        $this->assign('query',$query);
        $this->log(__CLASS__, __FUNCTION__, "门店会员-列表页", 1, 'view');
        return $this->fetch('Member/memberStoreList/memberList');
    }

    /**
     * Info: 红娘团队
     * Date: 2022/11/14 14:46
     */
    function redMotherTeam()
    {
        $user_id = input('user_id');
        $this->getSetMenu($this);
        $firSql = <<< SQL
SELECT b.id,a.nick_name title,b.one_user_id,b.two_user_id,b.user_id,b.pid,b.use_level
    FROM `base_user` a
        INNER JOIN `hfztcy_member_distribute` b
            ON `a`.`id` = `b`.`user_id`
    WHERE (`b`.`one_user_id` = {$user_id} or `b`.`two_user_id` = {$user_id} or `b`.`user_id` = {$user_id}) AND FIND_IN_SET('3',identity)
SQL;
        $result = Db::query($firSql);
        $result = array_map(function ($item) use ($user_id) {
            if ($item['user_id'] == $user_id) {
                $item['pid'] = 0;
            }
            $findMemberRes = (new LibMember())->findMemberToUser($item['user_id']);
            if ($findMemberRes['errorCode'] == 0) {
                $memberIdentity = [
                    '游客',
                    '注册用户',
                    'vip会员',
                    '红娘',
                    '门店'
                ];
                // 身份
                $identityList = explode(',', $findMemberRes['data']['identity']);
                $identityList = array_map('intval', $identityList);
                foreach ($memberIdentity as $k => $v) {
                    if (!in_array($k, $identityList)) {
                        unset($memberIdentity[$k]);
                    }
                }
                $identity_text = implode(",", $memberIdentity);
                if (!empty($findMemberRes['data']['user_id'])) {
                    $item['title'] = $findMemberRes['data']['username'].' (昵称：'.$findMemberRes['data']['nick_name'].' 身份：'.$identity_text.')';
                } else {
                    $item['title'] = ($findMemberRes['data']['nick_name'] ?: '无昵称').' (身份：'.$identity_text.')';
                }
            } else {
                $item['title'] = ($findMemberRes['data']['nick_name'] ?: '无昵称').'(身份：游客)';
            }
            return $item;
        },$result);
        $data = $this->generateTree($result);
        //dump($data);die();
        $this->assign('data',json_encode($data,JSON_UNESCAPED_UNICODE));
        return $this->fetch('Member/redMotherTeam/redMotherTeam');
    }

    function generateTree($array){
        $items = array();
        foreach($array as $value){
            $items[$value['user_id']] = $value;
        }
        $tree = array();
        foreach($items as $key => $value){
            $items[$key]['spread'] = false;
            if(isset($items[$value['pid']])){
                $items[$value['pid']]['children'][] = &$items[$key];
            }else{
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }

    /**
     * 红娘团队-列表页
     */
    function memberRedMotherTeamList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "红娘团队-列表页", 1, 'view');
        return $this->fetch('Member/memberRedMotherTeamList/memberList');
    }

    /**
     * Info: 修改
     * Date: 2022/11/23 10:03
     */
    function editMember ()
    {
        $this->getMenu($this);
        $model = new LibMember();
        $memberInfo = $model->findMember(['user_id' => input('id')]);
        $memberInfo['data']['photo_list_str'] = $memberInfo['data']['photo_list'];
        $memberInfo['data']['photo_list'] = explode(',',$memberInfo['data']['photo_list']);
        $this->assign('memberInfo', $memberInfo['data']);
        return $this->fetch('Member/editMember/editMember');
    }

    /**
     * Info: 上传照片
     * Date: 2022/11/15 11:47
     */
    function uploadPhoto ()
    {
        $model = new LibMember();
        $result = $model->uploadMemberPhoto();
        $arr['code'] = 0;
        $arr['msg'] = '上传成功';
        $arr['data'] = [
            'src' => $result['data']['path']
        ];
        echo json_encode($arr);die();
    }

    /**
     * Info: 栏目认证视频封面图
     * Date: 2023/2/20 15:35
     */
//    function deleteImage ()
//    {
//        $user_id = input('user_id',0);
//        $type = input('type',0);
//        $vcrModel = new LibUserVideoAuth();
//        $findVcrRes = $vcrModel->findUserVideoAuth(['user_id' => $user_id,'type' => $type]);
//        if ($findVcrRes['errorCode'] == 0) {
//            $vcrModel->updateUserVideoAuth(['id' => $findVcrRes['data']['id']]]);
//            $imgs = $findVcrRes['data']['imgs'];
//            if (file_exists(ROOT_PATH.'public/'.$imgs)) {
//                unlink(ROOT_PATH.'public/'.$imgs);
//                $vcrModel->updateUserVideoAuth(['id' => $findVcrRes['data']['id']], ['imgs' => '']);
//            }
//        }
//        echo json_encode(Common::errorArray(0, '删除成功', true));
//        die;
//    }

    /**
     * Info: 平台上传红娘视频资料
     * Date: 2022/11/15 11:47
     */
    function uploadVcr()
    {
        $this->getSetMenu($this);
        $vcrModel = new LibUserVideoAuth();
        $findVcrRes = $vcrModel->findUserVideoAuth(['user_id' => input('user_id'),'type' => input('type'),'is_delete' => 0]);
        if ($findVcrRes['errorCode'] == 0) {
            $configModel = new LibConfig();
            $findConfigRes = $configModel->findConfig(['item_key' => 'red_mother_posters_img']);
            $findVcrRes['data']['imgs'] = $findConfigRes['data']['item_value'];
            if ($findVcrRes['data']['video_url']) {
                $findVcrRes['data']['video_url'] = str_replace('upload/','upload/sliceVideo/',$findVcrRes['data']['video_url']);
            } else {
                $findVcrRes['data']['video_url'] = '';
            }
            $findVcrRes['data']['filename'] = "";
            if (isset($findVcrRes['data']['imgs']) && $findVcrRes['data']['imgs']) {
                $findVcrRes['data']['filename'] = pathinfo($findVcrRes['data']['imgs'],PATHINFO_FILENAME);
                $findVcrRes['data']['filename'] = str_replace('_thumb','',$findVcrRes['data']['filename']);
            }
            $this->assign('info',$findVcrRes['data']);
        } else {
            $this->assign('info',['video_url' => '']);
        }
        return $this->fetch('Member/uploadVcr/uploadVcr');
    }

    /**
     * Info: 添加VCR视频
     * Date: 2022/11/9 16:09
     */
    function addVcr ()
    {
        $user_id = input('user_id',0);
        $type = (int)input('type',0);

        $memberModel = new LibMember();
        $findMemberRes = $memberModel->findMember(['user_id' => $user_id]);
        if ($findMemberRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1, '用户不存在', []));
            die;
        }

        if ($type && strpos($findMemberRes['data']['state'],'3') === false) {
            echo json_encode(Common::errorArray(1, '当前用户不是红娘身份', []));
            die;
        }

        if (input('video_url') == '') {
            echo json_encode(Common::errorArray(1, '请上传视频', []));
            die;
        }

        // 保存vcr视频
        $vcrModel = new LibUserVideoAuth();
        $findVcrRes = $vcrModel->findUserVideoAuth(['user_id' => $user_id,'type' => $type,'is_delete' => 0]);

        //上传视频封面
        $imgs = null;
        $imgFlagCover = input('imgFlagCover',0);
        if ($imgFlagCover == '1') {
            $result = $memberModel->uploadVcrImgs();
            if ($result['errorCode'] == 0) {
                // 删除旧照片
                if ($findVcrRes['errorCode'] == 0 && $findVcrRes['data']['imgs']) {
                    file_exists(ROOT_PATH.'public/'.$findVcrRes['data']['imgs']) && unlink(ROOT_PATH.'public/'.$findVcrRes['data']['imgs']);
                    file_exists(ROOT_PATH.'public/'.str_replace('_thumb','',$findVcrRes['data']['imgs'])) && unlink(ROOT_PATH.'public/'.str_replace('_thumb','',$findVcrRes['data']['imgs']));
                }
                $imgs = $result['data']['path'];
            } elseif ($result['errorCode'] == 1) {
                echo json_encode(Common::errorArray(1, $result['errorInfo'], []));
                die;
            } elseif ($result['errorCode'] == 2) {
                echo json_encode(Common::errorArray(1, '请上传视频封面图', []));
                die;
            }
        } else {
            $configModel = new LibConfig();
            $findConfigRes = $configModel->findConfig(['item_key' => 'red_mother_posters_img']);
            $imgs = $findConfigRes['data']['item_value'];
        }

        if ($findVcrRes['errorCode'] == 0) {
            $vcrId = $findVcrRes['data']['id'];
            $vcrModel->updateUserVideoAuth(['id' => $vcrId],[
                'user_id' => $user_id,
                'order_id' => $findVcrRes['data']['order_id'],
                'imgs' => $imgs,
                'video_url' => $findVcrRes['data']['video_url'] ? : input('video_url'),
                'add_time' => Common::getTime(),
                'type' => $type,
                'is_fullscreen_video' => 0
            ]);
        } else {
            $res = $vcrModel->addUserVideoAuth([
                'user_id' => $user_id,
                'order_id' => 0,
                'imgs' => $imgs,
                'video_url' => input('video_url'),
                'add_time' => Common::getTime(),
                'type' => $type,
                'is_fullscreen_video' => 0
            ]);
            $vcrId =  $res['data'];
        }

        // 更新状态
        if ($type == 2) {
            if ($findMemberRes['data']['sex'] == '女') {
                $marriage = '签约红娘';
            } else {
                $marriage = '签约月老';
            }

            $arr = [
                'is_red_mother_video' => $vcrId,
                'marriage' => $marriage
            ];//红娘视频认证
        } else {
            $arr = ['is_vip_video' => $vcrId];//普通会员或者VIP会员视频认证
        }
        $arr && (new LibMember())->updateMember(['user_id' => $user_id] , $arr);

        echo json_encode(Common::errorArray(0, '上传成功', true));
        die;
    }

    /**
     * Info: 删除红娘视频
     * Date: 2023/2/16 13:52
     */
    function deleteVideoUrl ()
    {
        $user_id = input('user_id',0);
        $type = input('type',0);
        $vcrModel = new LibUserVideoAuth();
        $findVcrRes = $vcrModel->findUserVideoAuth(['user_id' => $user_id,'type' => $type,'is_delete' => 0]);
//        if (input('video_url') != $findVcrRes['data']['video_url']) {
//            $video_url = $findVcrRes['data']['video_url'];
//            $video_url = str_replace('upload/','upload/sliceVideo/',$video_url);
//            if (file_exists(ROOT_PATH.'public/'.$video_url)) {
//                unlink(ROOT_PATH.'public/'.$video_url);
//                $vcrModel->updateUserVideoAuth(['id' => $findVcrRes['data']['id']], ['video_url' => '']);
//            }
//        }
        if ($findVcrRes['errorCode'] == 0) {
            $vcrModel->updateUserVideoAuth(['id' => $findVcrRes['data']['id']],['is_delete' => 1]);
        }
        echo json_encode(Common::errorArray(0, '删除成功', true));
        die;
    }

    /**
     * Info: 处理会员修改
     * Date: 2022/11/23 10:06
     */
    function updateMember ()
    {
        $args = input();
        $model = new LibMember();
        $verifyRes = $model->goCheck($args, 'photo');
        if ($verifyRes['errorCode'] == 0) {
            $findMemberRes = $model->findMember(['user_id' => $args['user_id']]);
            if ($findMemberRes['errorCode'] == 0 && $findMemberRes['data']['audit_state'] == 0) {
                echo json_encode(Common::errorArray(1, '审核中不能修改相册', false));
                die;
            }
            unset($args['file']);
            $photos = [];
            if ($findMemberRes['data']['photo_list']) $photos = explode(',',$findMemberRes['data']['photo_list']);
            $photo_list = explode(',',$args['photo_list']);
            $args['photo_list'] = implode(',',array_merge($photos,$photo_list));
            $result = $model->updateMember(array("user_id" => $args['user_id']), $args);
            if ($result['errorCode'] == 1) {
                echo json_encode(Common::errorArray(1, $result['errorInfo'], false));
                die;
            }
        } else {
            echo json_encode(Common::errorArray(1, $verifyRes['errorInfo'], false));
            die;
        }

        $this->log(__CLASS__, __FUNCTION__, "更新", 0, 'update');
        echo json_encode($result);
    }

    /**
     * 详细页面
     */
    function detailMember()
    {
        $id =  input("id");
        $this->getMenu($this);
        //$memberInfo = $this->model->findMember(['id' => $id]);
        $sql = <<< SQL
select a.*,b.nick_name,b.head_img_url 
from `hfztcy_user` as a 
    inner join `base_user` as b on a.user_id = b.id 
where a.user_id = {$id}
SQL;
        $memberInfo = Db::query($sql);
        // 默认照片
        $memberInfo[0]['user_img'] = null;
        if(isset($memberInfo[0]['photo_list']) && $memberInfo[0]['photo_list']) {
            $user_img_list = explode(',',$memberInfo[0]['photo_list']);
            $memberInfo[0]['user_img'] = ROOT_URL.'/'.$user_img_list[0];
        }
        $this->assign('memberInfo', $memberInfo[0]);
        $this->log(__CLASS__, __FUNCTION__, "详情页面", 1, 'view');
        return $this->fetch("Member/memberDetail/memberDetail");
    }

    /**
     * 删除
     */
//    function deleteMember()
//    {
//        $id = input("id");
//        $findRes = $this->model->findMember(['id' => $id]);
//        if ($findRes['errorCode'] == 0) {
//            $this->model->deleteMember($id);
//            echo json_encode(Common::errorArray(0, '删除成功', true));
//            die();
//        }
//        echo json_encode(Common::errorArray(1, '用户不存在', false));
//        die();
//    }

    /**
     * Info: 用户VIP信息
     * Date: 2022/11/14 15:47
     */
    function getUserVipInfo ()
    {
        $this->getSetMenu($this);
        $id = input('id');
        $findRes = $this->model->findMember(['user_id' => $id]);
        if ($findRes['errorCode'] == 0) {
            if ($findRes['data']['is_vip']) {
                $orderModel = new LibOrderVip();
                $findOrderRes = $orderModel->findOrder(['order_id' => $findRes['data']['is_vip']]);
                $findOrderRes['data']['vip_info'] = json_decode($findOrderRes['data']['vip_info'],true);
               $findRes['data']['order'] = $findOrderRes['data'];
            }
        }
        $findRes['data']['vip_open_time'] = date('Y-m-d H:i:s',$findRes['data']['vip_open_time']);
        $this->assign('memberInfo',$findRes['data']);
        return $this->fetch("Member/vipInfo/vipInfo");
    }

    /**
     * Info: 红娘团队
     * Date: 2022/11/10 13:59
     */
    function pagingRedMotherTeam ()
    {
        $args = $this->getArgsList($this, ['nick_name','username','startTime','endTime','pid','identity','user_id']);
        $page = $this->getPageInfo();
        $where = [];
        //if ($args['identity'] != '') $where[] = "FIND_IN_SET({$args['identity']},identity)";
        if (!empty($args['nick_name'])) $where[] = "`a`.`nick_name` like '%" . $args['nick_name'] . "%'";
        if (!empty($args['username'])) $where[] = "`a`.`username` like '%" . $args['username'] . "%'";
        if (!empty($args['pid'])) $where[] = "`a`.`parent_id` = '" . $args['pid'] . "'";
        $one_user_id = $two_user_id = 0;
        if (!empty($args['user_id'])) {
            $model = new LibMemberDistribute();
            $findPartnerDistribute = $model->findMemberDistribute(['user_id' => $args['user_id']]);
            if ($findPartnerDistribute['errorCode'] == 0)
            {
                $one_user_id = $findPartnerDistribute['data']['one_user_id'];
                $two_user_id = $findPartnerDistribute['data']['two_user_id'];
                $condition[] = "(`a`.`user_id` = {$one_user_id} OR `a`.`user_id` = {$two_user_id})";
            }
            $condition[] = "(`a`.`user_id` = {$args['user_id']} OR `a`.`one_user_id` = {$args['user_id']} OR `a`.`two_user_id` = {$args['user_id']})";
            $where[] = '('.implode(' OR ',$condition).')';
        }
        if (!empty($args['startTime'])) $where[] = "`a`.`add_time` >= '" . $args['startTime'] . "'";
        if (!empty($args['endTime'])) $where[] = "`a`.`add_time` <= '" . $args['endTime'] . ' 23:59:59' . "'";
        $result = $this->model->pagingRedMotherTeam($page,  implode(' AND ', $where), 'cid ASC');
        foreach ($result['data']['dataList'] as &$item) {
            if ($one_user_id && $item['user_id'] == $one_user_id) $item['level'] = '上一级';
            if ($two_user_id && $item['user_id'] == $two_user_id) $item['level'] = '上二级';
            if ($args['user_id'] == $item['user_id']) $item['level'] = '本级';
            if ($args['user_id'] == $item['one_user_id']) $item['level'] = '下一级';
            if ($args['user_id'] == $item['two_user_id']) $item['level'] = '下二级';
        }
        echo json_encode($this->handleSearchMemberItem($result));
    }

    /**
     * Info: 会员团队
     * Date: 2022/11/10 13:59
     */
    function pagingMemberTeam ()
    {
        $args = $this->getArgsList($this, ['nick_name','username','startTime','endTime','pid','is_disabled','identity']);
        $page = $this->getPageInfo();
        $where = [];
        if ($args['identity'] != '') {
            if ($args['identity'] != 5) {
                $where[] = "FIND_IN_SET({$args['identity']},identity)";
            } else {
                $where[] = "(`a`.`is_vip_video` > 0 or `a`.`is_red_mother_video` > 0)";
            }
        }
        if (!empty($args['nick_name'])) $where[] = "`a`.`nick_name` like '%" . $args['nick_name'] . "%'";
        if (!empty($args['username'])) $where[] = "`a`.`username` like '%" . $args['username'] . "%'";
        if (!empty($args['pid'])) $where[] = "`a`.`parent_id` = '" . $args['pid'] . "'";
        if (!empty($args['startTime'])) $where[] = "`a`.`add_time` >= '" . $args['startTime'] . "'";
        if (!empty($args['endTime'])) $where[] = "`a`.`add_time` <= '" . $args['endTime'] . ' 23:59:59' . "'";
        if (($args['is_disabled'] == 0 || $args['is_disabled'] == 1) && $args['is_disabled']!= '') $where[] = "`a`.`is_disabled` = '" . $args['is_disabled'] . "'";
        $result = $this->model->pagingMemberTeam($page,  implode(' AND ', $where));
        echo json_encode($this->handleSearchMemberItem($result));
    }

    /**
     * Info: 游客
     * Date: 2022/11/10 13:59
     */
    function pagingGuest ()
    {
        $args = $this->getArgsList($this, ['nick_name','startTime','endTime','pid','identity']);
        $page = $this->getPageInfo();
        $where = [];
        if ($args['identity'] != '') $where[] = "`a`.`identity` = 0";
        if (!empty($args['nick_name'])) $where[] = "`a`.`nick_name` like '%" . $args['nick_name'] . "%'";
        if (!empty($args['pid'])) $where[] = "`a`.`parent_id` = '" . $args['pid'] . "'";
        if (!empty($args['startTime'])) $where[] = "`a`.`add_time` >= '" . $args['startTime'] . "'";
        if (!empty($args['endTime'])) $where[] = "`a`.`add_time` <= '" . $args['endTime'] . ' 23:59:59' . "'";
        $result = $this->model->pagingGuest($page,  implode(' AND ', $where));
        echo json_encode($this->handleSearchMemberItem($result));
    }

    /**
     * 分页查询
     */
    function pagingMember()
    {
        $args = $this->getArgsList($this, ['nick_name','phone','startTime','endTime','user_id','pid','identity','username','auth_state','is_disabled','marriage','sex']);
        $page = $this->getPageInfo();
        $where = [];
        if ($args['identity'] != '') {
            if ($args['identity'] == 0) {
                $where[] = "(`a`.`audit_state` = 0 OR `a`.`audit_state` = 2)";
            } else {
                $where[] = "FIND_IN_SET({$args['identity']},identity)";
                $where[] = "`a`.`audit_state` = 1";
            }
        }
        if (!empty($args['auth_state'])) $where[] = "`a`.`is_vip_video` > 0";
        if (!empty($args['nick_name'])) $where[] = "`a`.`nick_name` like '%" . $args['nick_name'] . "%'";
        if (!empty($args['username'])) $where[] = "`a`.`username` like '%" . $args['username'] . "%'";
        if (($args['is_disabled'] == 0 || $args['is_disabled'] == 1) && $args['is_disabled']!= '') $where[] = "`a`.`is_disabled` = '" . $args['is_disabled'] . "'";
        if (!empty($args['user_id'])) $where[] = "`a`.`user_id` = '" . $args['user_id'] . "'";
        if (!empty($args['pid'])) $where[] = "`a`.`parent_id` = '" . $args['pid'] . "'";
        if (!empty($args['phone'])) $where[] = "`a`.`mobile` = '" . $args['phone'] . "'";
        if (!empty($args['state'])) $where[] = "`a`.`state` = '" . $args['state'] . "'";
        if (!empty($args['marriage'])) $where[] = "`a`.`marriage` = '" . $args['marriage'] . "'";
        if (!empty($args['sex'])) $where[] = "`a`.`sex` = '" . $args['sex'] . "'";
        if (!empty($args['startTime'])) $where[] = "`a`.`add_time` >= '" . $args['startTime'] . "'";
        if (!empty($args['endTime'])) $where[] = "`a`.`add_time` <= '" . $args['endTime'] . ' 23:59:59' . "'";
//        dump(implode(' AND ', $where));
        $result = $this->model->pagingMember($page,  implode(' AND ', $where));
        echo json_encode($this->handleSearchMemberItem($result));
    }

    /**
     * Info: 用户数据处理
     * Date: 2022/11/11 9:23
     */
    private function handleSearchMemberItem ($result)
    {
        foreach ($result['data']['dataList'] as &$item) {
            // 会员身份
            $memberIdentity = [
                '游客',
                '注册用户',
                'vip会员',
                '红娘',
                '门店'
            ];
            $identityIndex = [0,1,2,3,4];

            // 默认照片
            $item['user_img'] = null;
            if(isset($item['photo_list']) && $item['photo_list']) {
                $user_img_list = explode(',',$item['photo_list']);
                $item['user_img'] = $user_img_list[0];
            }

            // 开通的套餐
            $item['vip_info'] = [];
            if (isset($item['is_vip']) && $item['is_vip']) {
                $sql = <<< SQL
SELECT vip_info FROM `hfztcy_order_vip` WHERE `order_id` = {$item['is_vip']}
SQL;
                $res = Db::query($sql);
                if ($res) {
                    $item['vip_info'] = json_decode($res[0]['vip_info'],true);
                }
            }

            // vip开通时间戳
            if (isset($item['vip_open_time']) && $item['vip_open_time']) {
                $item['is_vip_overdue'] = ($item['vip_open_time'] < time()) ? 1 : 0;//vip是否过期
                $item['vip_open_time'] = date('Y-m-d',$item['vip_open_time']);
            }

            // 身份
            $identityList = explode(',',$item['identity']);
            $identityList = array_map('intval',$identityList);
            foreach ($memberIdentity as $k => $v) {
                if (!in_array($k,$identityList)) {
                    unset($memberIdentity[$k]);
                    unset($identityIndex[$k]);
                }
                if ($v == 'vip会员') {
                    if (isset($item['is_vip_overdue']) && $item['is_vip_overdue']) {
                        $memberIdentity[$k] = $v.'(过期)';
                    }
                }
            }
            $item['identity_text'] = implode("<br/>",$memberIdentity);
            $item['identity_list'] = array_values($memberIdentity);

            // 上级推荐人
            $item['identity_tjr'] = '';
            $parent_id = $item['parent_id'];
            if ($parent_id) {
                $sql = <<< SQL
SELECT b.username
FROM `hfztcy_member_distribute` AS a
    LEFT JOIN `hfztcy_user` AS b
        ON a.user_id = b.user_id
WHERE b.`user_id` = {$parent_id}
ORDER BY a.id desc LIMIT 0,1
SQL;
                $query = Db::query($sql);
                if ($query) {
                    $username = $query[0]['username'];
                    $item['identity_tjr'] = "<br/>推荐人：<span class='username' style='color: green'>{$username}</span>";
                    $item['identity_text'] .= $item['identity_tjr'];
                }
            }

            $identityIndex = array_values($identityIndex);
            // 对于 hfztcy_user_video_auth 表状态， 0普通会员 1vip认证 2红娘认证 3门店认证
            if (count($identityIndex) > 1) {
                $identity_id = max($identityIndex);
                if ($identity_id == 3) $item['type'] = 2;
                if ($identity_id == 4) $item['type'] = 3;
            } else {
                if ($identityIndex[0] == 1) $item['type'] = 0;
                if ($identityIndex[0] == 2) $item['type'] = 1;
                if ($identityIndex[0] == 3) $item['type'] = 2;
                if ($identityIndex[0] == 4) $item['type'] = 3;
            }

            // 视频认证视频
            $item['vip_auth_video'] = '';
            if (isset($item['is_vip_video']) && $item['is_vip_video']) {
                $sql = <<< SQL
SELECT * FROM `hfztcy_user_video_auth` WHERE `user_id` = {$item['user_id']} AND `id` = {$item['is_vip_video']} AND `is_delete` = 0
SQL;
                $res = Db::query($sql);
                if ($res && $res[0]['video_url']) {
                    if (file_exists(ROOT_PATH.'public/'.str_replace('upload/','upload/sliceVideo/',$res[0]['video_url']))) {
                        $item['vip_auth_video'] = ROOT_URL.'/'.str_replace('upload/','upload/sliceVideo/',$res[0]['video_url']);
                    }
                }
            }

            // 红娘认证视频
            $item['red_mother_auth_video'] = '';
            if (isset($item['is_red_mother_video']) && $item['is_red_mother_video']) {
                $sql = <<< SQL
SELECT * FROM `hfztcy_user_video_auth` WHERE `user_id` = {$item['user_id']} AND `id` = {$item['is_red_mother_video']} AND `is_delete` = 0
SQL;
                $res = Db::query($sql);
                if ($res && $res[0]['video_url']) {
                    if (file_exists(ROOT_PATH.'public/'.str_replace('upload/','upload/sliceVideo/',$res[0]['video_url']))) {
                        $item['red_mother_auth_video'] = ROOT_URL . '/' . str_replace('upload/', 'upload/sliceVideo/', $res[0]['video_url']);
                    }
                }
            }

            // 是否开通红娘
            $item['is_red_mother'] = strpos($item['identity'],'3') !== false ? 1 : 0;

            // 是否开通门店
            $item['is_store'] = strpos($item['identity'],'4') !== false ? 1 : 0;

            // 门店认证视频
            $item['store_auth_video'] = '';
            if (isset($item['is_store']) && $item['is_store']) {
                $sql = <<< SQL
SELECT vcr FROM `hfztcy_store` WHERE `uid` = {$item['user_id']}
SQL;
                $res = Db::query($sql);
                if ($res && $res[0]['vcr']) {
                    if (file_exists(ROOT_PATH.'public/'.str_replace('upload/','upload/sliceVideo/',$res[0]['vcr']))) {
                        $item['store_auth_video'] = ROOT_URL . '/' . str_replace('upload/', 'upload/sliceVideo/', $res[0]['vcr']);
                    }
                }
            }

            // 会员团队数量
            $item['member_team_count'] = 0;
            $item['red_mother_team_count'] = 0;
            $item['like_num'] = 0;
            $item['fans_num'] = 0;
            if (isset($item['id']) && $item['id']) {
                $sql = <<< SQL
SELECT count(*) as num FROM `base_user` WHERE `parent_id` = {$item['id']}
SQL;
                $res = Db::query($sql);
                if ($res) {
                    $item['member_team_count'] = $res[0]['num'];
                }
                // 红娘数量
                $sql = <<< SQL
    SELECT count(*) as num FROM `base_user` WHERE `parent_id` = {$item['id']} AND FIND_IN_SET(3,identity);
SQL;
                $res = Db::query($sql);
                if ($res) {
                    $item['red_mother_team_count'] = $res[0]['num'];
                }
                // 喜欢数/粉丝数
                //喜欢数
                $sql = <<< SQL
    SELECT count(*) as num FROM `hfztcy_collect` WHERE `user_id` = {$item['id']}
SQL;
                $res = Db::query($sql);
                if ($res) {
                    $item['like_num'] = $res[0]['num'];
                }
                //粉丝数
                $sql = <<< SQL
    SELECT count(*) as num FROM `hfztcy_collect` WHERE `like_user_id` = {$item['id']}
SQL;
                $res = Db::query($sql);
                if ($res) {
                    $item['fans_num'] = $res[0]['num'];
                }
            }
        }

        return $result;
    }

    /**
     * Info: 审核用户
     * Date: 2022/6/20 11:24
     */
    public function auditStatus()
    {
        $id = input("id");
        $status = input("state");

        $result = $this->model->findMember(['user_id' => $id]);
        if ($result['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1, '不存在', ''));
            die();
        }
        if ($result['data']['audit_state'] > 0) {
            echo json_encode(Common::errorArray(1, '已审核', ''));
            die();
        }

        $data = [];
        Db::startTrans();
        try {
            $findUserRes = (new LibUser())->findUser(['id' => $id]);
            $template_id4 = "r9ughXN_w4uM4NJ6LSDXICjUKy09loh7A9qa_Mr1lts";
            $openid = $findUserRes['data']['account'];
            if ($status == 1) {
                $reason = '审核成功';

                $data['state'] = 1;//普通会员
                (new LibUser())->updateUser(['id' => $id] , ['identity' => 1]);//修改微信用户表身份字段
                // 给用户发送注册审核模板消息
                $data4 = [
                    'first'=>array('value'=>'注册资料已审核', 'color'=>'#173177'),
                    'keyword1'=>array('value'=>'用户编号：'.$id, 'color'=>'#173177'),
                    'keyword2'=>array('value'=>$reason, 'color'=>'#173177'),
                    'remark'=>array('value'=>'缘份驿站感谢您的加入。', 'color'=>'#173177'),
                ];
                \wechatUtil\TemplateMessage::sendTemplateMessage($data4,$openid,$template_id4);
            } else {
                $reason = input("reason");
                // 给用户发送注册审核模板消息
                $data4 = [
                    'first'=>array('value'=>'注册资料已审核', 'color'=>'#173177'),
                    'keyword1'=>array('value'=>'用户编号：'.$id.'，审核未通过：'.$reason, 'color'=>'#173177'),
                    'keyword2'=>array('value'=>'审核未通过', 'color'=>'#173177'),
                    'remark'=>array('value'=>'请根据提示，修改资料中不规范或者错误的信息并提交审核。', 'color'=>'#173177'),
                ];
                \wechatUtil\TemplateMessage::sendTemplateMessage($data4,$openid,$template_id4);
            }
            $data['audit_state'] = $status;
            $data['audit_msg'] = $reason;
            $data['audit_time'] = Common::getTime();

            $this->model->updateMember(['user_id' => $id], $data);
            $code = 0;
            $msg = "更新成功";
            $flag = true;
            Db::commit();
        } catch (ErrorException $exception) {
            $code = 1;
            $msg = "更新失败" . $exception->getMessage();
            $flag = false;
            Db::rollback();
        }
        echo json_encode(Common::errorArray($code, $msg, $flag));
        die();
    }

    /**
     * Info: 审核用户
     * Date: 2022/6/20 11:24
     */
    public function disabledStatus()
    {
        $id = input("id");
        $status = input("state");

        $result = $this->model->findMember(['user_id' => $id]);
        if ($result['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1, '不存在', ''));
            die();
        }

        $result = $this->model->updateMember(['user_id' => $id], ['is_disabled' => $status]);
        echo json_encode($result);
        die();
    }

    /**
     * Info: 批量修改会员婚姻
     * Date: 2023/1/12 16:27
     */
    public function batchMemberInfo ()
    {
        $ids = input('ids');
        $name = input('name');
        if ($ids == '' || $ids == null) {
            echo json_encode(Common::errorArray(1, '请选择用户', ''));
            die();
        }
        $this->model->updateMember(['user_id' => ['in',$ids]],['marriage' => $name]);
        echo json_encode(Common::errorArray(0,'修改成功',false));
        die();
    }

    /**
     * Info: 批量修改会员身份
     * Date: 2023/1/12 16:27
     */
    public function batchMemberIdentity ()
    {
        $ids = input('ids');
        if ($ids == '' || $ids == null) {
            echo json_encode(Common::errorArray(1, '请选择用户', ''));
            die();
        }
        $newIds = [];
        $guestIds = [];
        $userModel = new LibUser();
        $findUserRes = $userModel->findAllUser(['id' => ['in',$ids]]);
        if ($findUserRes['errorCode'] == 0) {
            foreach ($findUserRes['data'] as $item) {
                if (strpos($item['identity'],'0') !== false) {
                    $guestIds[] = $item['id'];
                } else {
                    $newIds[] = $item['id'];
                }
            }
        }
        if (!$newIds) {
            echo json_encode(Common::errorArray(1, '游客身份暂不能设置为红娘', ''));
            die();
        }
        $ids = implode(',',$newIds);
        $userModel->updateUser(['id' => ['in',$ids]],['identity' => 3]);
        $this->model->updateMember(['user_id' => ['in',$ids]],['state' => 3]);
        echo json_encode(Common::errorArray(0,'修改成功，更改数量：'.count($newIds),false));
        die();
    }

    /**
     * Info: 撤销红娘
     * Date: 2023/2/22 18:21
     */
    public function updateRedMotherIdentity ()
    {
        $ids = input('ids');
        if ($ids == '' || $ids == null) {
            echo json_encode(Common::errorArray(1, '请选择用户', ''));
            die();
        }
        $newIds = [];
        $guestIds = [];
        $userModel = new LibUser();
        $findUserRes = $userModel->findAllUser(['id' => ['in',$ids]]);
        if ($findUserRes['errorCode'] == 0) {
            foreach ($findUserRes['data'] as $item) {
                if (strpos($item['identity'],'0') !== false) {
                    $guestIds[] = $item['id'];
                } else {
                    $newIds[] = $item['id'];
                }
            }
        }
//        if (!$newIds) {
//            echo json_encode(Common::errorArray(1, '游客身份暂不能设置为红娘', ''));
//            die();
//        }
        $ids = implode(',',$newIds);
        $userModel->updateUser(['id' => ['in',$ids]],['identity' => 1]);
        $this->model->updateMember(['user_id' => ['in',$ids]],['state' => 1]);
        echo json_encode(Common::errorArray(0,'修改成功，更改数量：'.count($newIds),false));
        die();
    }

    /**
     * Info: 替换上级
     * Date: 2023/2/23 14:26
     */
    function replaceUserReferrer ()
    {
        $replace_user_id = input('replace_user_id');//推荐人
        $cur_user_id = input('cur_user_id');//用户
        $distributeModel = new \app\common\model\hfztcy\LibMemberDistribute();
        $userModel = new LibUser();
        $findDistributeRes = $distributeModel->findMemberDistribute(['user_id' => $replace_user_id]);
        if ($findDistributeRes['errorCode'] == 1) {
            $findUserRes = $userModel->findUser(['id' => $replace_user_id]);
            if ($findUserRes['errorCode'] == 1) {
                $two_user_id = 0;
            } else {
                $two_user_id = $findUserRes['data']['parent_id'];
            }
        } else {
            $two_user_id = $findDistributeRes['data']['one_user_id'];
        }
        $findCurUserRes = $userModel->findUser(['id' => $cur_user_id]);
        // 记录团队变动
        $data = [];
        $data['user_id'] = $cur_user_id;
        $data['old_user_id'] = $findCurUserRes['data']['parent_id'];
        $data['cur_user_id'] = $replace_user_id;
        $data['add_time'] = Common::getTime();
        (new LibMemberTeamChange())->addMemberTeamChange($data);
        // 更新用户表parent_id字段
        $userModel->updateUser(['id' => $cur_user_id], ['parent_id' => $replace_user_id]);
        // 更新当前扫码用户上一级层级关系
        $distributeModel->updateMemberDistribute(['user_id' => $cur_user_id] , [
            'pid' => $replace_user_id,
            'one_user_id' => $replace_user_id,
            'two_user_id' => $two_user_id
        ]);
        // 更新当前扫码用户上二级层级关系
        $distributeModel->updateMemberDistribute(['one_user_id' => $cur_user_id] , [
            'two_user_id' => $replace_user_id
        ]);
        $findMemberRes = (new LibMember())->findMember(['user_id' => $replace_user_id]);
        echo json_encode(Common::errorArray(0,'修改成功',['username' => $findMemberRes['data']['username']]));
        die();
    }
}

?>